﻿using Abp.Extensions;
using Mt.Site.Core.WorkFlows.Enum;
using Mt.Site.Core.WorkFlows.Process;
using Mt.Site.Core.WorkFlows.Process.Impl;
using System.Threading.Tasks;

namespace Mt.Site.Core.WorkFlows.Diy.Actions.Impl
{
    public class NotAgreeAction : ActionBase
    {
        public override string UniqueName => WorkFlowConst.OperationName.NotAgreeAction;

        public override Task<string> DisplayName(IWorkFlowManager manager)
        {
            return Task.FromResult("不同意");
        }

        public override async Task<bool> IsShowAsync(IWorkFlowManager manager)
        {
            var actionState = await manager.CheckActionStateAsync();
            var isBranchLine = await manager.IsBranchLineAsync();
            var canOperate = manager.CanOperate(UniqueName);

            //当前是待办，并且没有后续步骤
            if (actionState == ActionState.Todo
                && !isBranchLine
                && canOperate)
            {
                return true;
            }
            return false;
        }

        public override async Task OperateAsync(IWorkFlowManager manager, object data)
        {
            var isShow = await IsShowAsync(manager);
            if (isShow)
            {
                //await manager.WorkFlowPluginFunction.BeforeFinishedAsync(manager);

                //信息稿件状态切换为办结,文件状态改为发布状态
                var entity = manager.CurrentPaper.Paper;
                entity.ChangePaperState(PaperState.Finished);
                entity.ChangeApprovalResult(ApprovalResult.Reject);//不同意

                //状态数据切换为已处理
                var current = await manager.GetCurrentProcessAsync();

                // 查找未办理的人员，自动提交任务，标记不在表格中显示，任务提交到下一步
                var isHasOther = await manager.IsHasOtherOperatorAsync(current);
                if (isHasOther)
                {
                    var otherOperatorData = await manager.As<WorkFlowManager>().GetAllOtherOperatorAsync(current);
                    foreach (var item in otherOperatorData)
                    {
                        manager.ChangeProcessDataToArchive(current,item);
                        await manager.WorkFlowProcessStore.UpdateAsync(item);
                    }
                }

                var args = data as ActionArgs;
                if (args.ReplyMsg.IsNullOrEmpty())
                {
                    args.ReplyMsg = "不通过";
                }
                await manager.HasSolved(args.ReplyMsg, "不通过", MoveMode.End);

                //写入日志
                await manager.AddLogAsync("办结", manager.UserId, null, current?.Id);

                //await manager.WorkFlowPluginFunction.AfterFinishedAsync(manager);
            }
        }

        public override bool NeedReply(IWorkFlowManager manager)
        {
            return false;
        }

        public override bool NeedCheckState => false;
    }
}